package com.tabbinder.server;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.tabbinder.client.Constants;

/**
 * Tiny servlet to get the user name and logout URL for web interface
 * 
 * @author Tatiana Kichkaylo
 */
public class WhoAmIServlet extends HttpServlet {
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		PrintWriter out = resp.getWriter();

		// Same logic as CommonServlet.getUser(). We are not using that method
		// here, because we need access to the user service to get logout URL
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		if (user == null) {
			resp.setStatus(Constants.STATUS_CODE_UNAUTHORIZED);
			// Note that the request URL is for data, so we redirect to the
			// root instead. Plug-ins care only for the code and not the URL
			// anyway.
			out.append(userService.createLoginURL(Constants.HOME_URL));
		} else {
			out.append(user.getNickname());
			out.append("\n");
			out.append(user.getEmail());
			out.append("\n");
			// This should double-redirect to login, unless we add default page
			out.append(userService.createLogoutURL(Constants.HOME_URL));
		}
	}
}
